package com.pan.crawler.impl3;

import com.pan.crawler.Directory;
import com.pan.entity.BookDirectory;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class DirectoryImpl3 implements Directory {
    private String website = "http://www.dawensk.com";
    //注意这个网站要进入到目录去爬

    public void checkUrl(String url){
        String websiteRegex = website;
        Pattern pattern = Pattern.compile(websiteRegex);
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find()){
            throw new RuntimeException("网站错误："+url+"，应该为："+website);
        }
    }

    @Override
    public BookDirectory get(String url) {
        checkUrl(url);
        EdgeDriver edgeDriver = new EdgeDriver();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        edgeDriver.navigate().to(url);
        String bookName = edgeDriver.findElement(By.className("top"))
                .findElement(By.cssSelector("a")).getText();
        List<WebElement> aList = edgeDriver.findElement(By.id("listsss")).findElements(By.cssSelector("a"));
        int[] i = new int[]{0};
        List<Chapter> chapterList = aList.stream().map(a->{
            String title = a.getText();
            String chapterUrl = a.getAttribute("href");
            return new Chapter().setTitle(title).setUrl(chapterUrl).setId(i[0]++);
        }).collect(Collectors.toList());
        edgeDriver.quit();
        return new BookDirectory().setBookName(bookName).setChapterList(chapterList);
    }
}
